import com.sun.xml.internal.ws.util.StringUtils;

import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Objects;

/**
 * @description:
 * @Author: wuzhenbin
 * @CreateTime: 2025-02-12
 */
public class leetcode_3 {
    public static void main(String[] args) {
        System.out.println(lengthOfLongestSubstring2("abcabcbb"));
    }

    private static boolean judge(String s) {
        HashSet<Character> characters = new HashSet<>();
        for (char c : s.toCharArray()) {
            characters.add(c);
        }
        if (characters.size() == s.length()) return true;
        return false;
    }


    public static int lengthOfLongestSubstring(String s) {
        if (Objects.equals(s, "") || s.isEmpty()) return 0;
        int left = 0;
        int res = 0;

        for (int i = 1; i < s.length() + 1; i++) {
            while (!judge(s.substring(left, i))) {
                left++;
            }
            res = Math.max(i - left, res);
        }
        return res;
    }


    public static int lengthOfLongestSubstring1(String s) {
        if (s == null || s.length() == 0) return 0;

        HashSet<Character> charSet = new HashSet<>();
        int left = 0, right = 0, maxLength = 0;

        while (right < s.length()) {
            // 如果没有重复字符，加入窗口
            if (!charSet.contains(s.charAt(right))) {
                charSet.add(s.charAt(right));
                right++;
                maxLength = Math.max(maxLength, right - left);
            } else {
                // 如果有重复字符，收缩窗口
                charSet.remove(s.charAt(left));
                left++;
            }
        }
        return maxLength;
    }

    public static int lengthOfLongestSubstring2(String s) {
        if (s == null || s.length() == 0) return 0;
        if(s.length()==1) return 1;
        int left = 0;
        int right = 0;
        int maxLength = 0;
        HashSet<Character> set = new HashSet<>();
        while(right<s.length()){
            if(!set.contains(s.charAt(right))){
                set.add(s.charAt(right));
                maxLength = Math.max(maxLength,right-left+1);
                right++;
            }
            //有重复 左边收缩
            else {
                while(set.contains(s.charAt(right))){
                    set.remove(s.charAt(left));
                    left++;
                }
                maxLength = Math.max(maxLength,right-left+1);
            }
        }
        return maxLength;
    }
}
